package com.lyz.moil.core.security.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lyz.moil.core.orm.hibernate.BaseDao;
import com.lyz.moil.core.orm.hibernate.BaseService;
import com.lyz.moil.core.security.dao.UserDao;
import com.lyz.moil.core.security.entity.Resources;
import com.lyz.moil.core.security.entity.Roles;
import com.lyz.moil.core.security.entity.User;

@Service
@Transactional
public class ResourcesService extends BaseService<Resources> {

	@Resource
	private UserDao userDao;

	@Override
	@Resource(name = "resourcesDao")
	public void setBaseDao(BaseDao<Resources> baseDao) {
		this.baseDao = baseDao;
	}

	public List<Resources> findMenu() {
		return baseDao.findList("from Resources where isMenu = 1 order by gorder");
	}

	public List<Resources> findMenu(Integer userId) {
		List<Resources> list = new ArrayList<Resources>();
		User user = userDao.find(userId);
		Set<Roles> roles = user.getRoles();
		for (Roles role : roles) {
			list.addAll(role.getResources());
		}
		List<Resources> listNotRepeat = new ArrayList<Resources>();
		for (Resources r : list) {
			if (!listNotRepeat.contains(r)) {
				listNotRepeat.add(r);
			}
		}
		Collections.sort(listNotRepeat, new SortByGorder());
		return listNotRepeat;
	}

	// 按gorder排序
	class SortByGorder implements Comparator<Resources> {
		@Override
		public int compare(Resources o1, Resources o2) {
			if (o1.getGroup().getGorder() < o2.getGroup().getGorder()) {
				return -1;
			} else if (o1.getGroup().getGorder() > o2.getGroup().getGorder()) {
				return 1;
			} else {
				if (o1.getGorder() < o2.getGorder()) {
					return -1;
				} else {
					return 1;
				}
			}
		}
	}
}
